#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <libnotify/notify.h>

// Custom gradient background view (core beautiful UI element)
@interface GradientBackgroundView : NSView
@end

@implementation GradientBackgroundView

- (void)drawRect:(NSRect)rect {
    [super drawRect:rect];
    
    // Soft blue-purple gradient (modern, eye-friendly color scheme)
    NSGradient *gradient = [[NSGradient alloc] initWithColorsAndLocations:
        [NSColor colorWithCalibratedRed:0.2 green:0.4 blue:0.8 alpha:1.0], 0.0,  // Top color
        [NSColor colorWithCalibratedRed:0.6 green:0.3 blue:0.9 alpha:1.0], 1.0,  // Bottom color
        nil];
    
    // Draw gradient to cover the entire view
    [gradient drawInRect:[self bounds] angle:270.0];  // 270° = top-to-bottom direction
    [gradient release];
}

@end

// Main app delegate
@interface BeautifulUIDelegate : NSObject <NSApplicationDelegate> {
    NSWindow *mainWindow;
    GradientBackgroundView *bgView;
}
- (void)playSound:(id)sender;
- (void)showNotification:(id)sender;
- (void)showNotificationWithMessage:(NSString *)message;
@end

@implementation BeautifulUIDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
    // Initialize libnotify for system notifications
    if (!notify_init("Beautiful GNUstep UI")) {
        NSLog(@"Failed to initialize libnotify");
        [NSApp terminate:nil];
    }

    // 1. Create main window (GNUstep-compatible, modern size)
    NSRect screenFrame = [[NSScreen mainScreen] frame];
    NSRect windowFrame = NSMakeRect(
        (screenFrame.size.width - 400) / 2,  // Center horizontally
        (screenFrame.size.height - 250) / 2, // Center vertically
        400, 250                             // Ideal size for modern UI
    );
    
    mainWindow = [[NSWindow alloc] initWithContentRect:windowFrame
                                            styleMask:NSWindowStyleMaskTitled | 
                                                     NSWindowStyleMaskClosable | 
                                                     NSWindowStyleMaskResizable
                                              backing:NSBackingStoreBuffered
                                                defer:NO];
    [mainWindow setTitle:@"Beautiful UI Demo"];
    [mainWindow setBackgroundColor:[NSColor clearColor]];  // Transparent for gradient background
    [mainWindow setHasShadow:YES];  // Keep shadow (supported by GNUstep), remove unsupported offset/blur

    // 2. Set gradient background (replace default plain view)
    bgView = [[GradientBackgroundView alloc] initWithFrame:NSMakeRect(0, 0, 400, 250)];
    [mainWindow setContentView:bgView];

    // 3. Add title label (white text with shadow for readability on gradient)
    NSTextField *titleLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 190, 400, 30)];
    [titleLabel setStringValue:@"Sound & Notification Center"];
    [titleLabel setFont:[NSFont fontWithName:@"Helvetica Bold" size:18]];
    [titleLabel setTextColor:[NSColor whiteColor]];
    [titleLabel setBackgroundColor:[NSColor clearColor]];  // Transparent background
    [titleLabel setBordered:NO];  // Remove default border
    [titleLabel setAlignment:NSCenterTextAlignment];  // Center align
    
    // Add subtle text shadow (prevents washing out on light gradient areas)
    NSMutableDictionary *shadowAttrs = [NSMutableDictionary dictionary];
    [shadowAttrs setObject:[NSShadow shadowWithBlurRadius:2.0 
                                                offset:NSMakeSize(0, -1) 
                                                color:[NSColor blackColor]] 
                    forKey:NSShadowAttributeName];
    [titleLabel setAttributedStringValue:[[NSAttributedString alloc] 
        initWithString:titleLabel.stringValue 
        attributes:shadowAttrs]];
    
    [bgView addSubview:titleLabel];
    [titleLabel release];

    // 4. Add Play Sound button (rounded, hover effect, GNUstep-compatible)
    NSButton *soundBtn = [[NSButton alloc] initWithFrame:NSMakeRect(50, 100, 140, 50)];
    [soundBtn setTitle:@"Play Sound"];
    [soundBtn setFont:[NSFont fontWithName:@"Helvetica" size:14]];
    [soundBtn setTextColor:[NSColor whiteColor]];
    [soundBtn setBezelStyle:NSRoundedBezelStyle];  // Supported rounded style
    [soundBtn setBordered:YES];  // Use system border (avoids layer issues)
    [soundBtn setTarget:self];
    [soundBtn setAction:@selector(playSound:)];
    // Hover effect: darken background when clicked/highlighted
    [soundBtn setHighlightedColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.3]];
    [bgView addSubview:soundBtn];
    [soundBtn release];

    // 5. Add Show Alert button (same style as sound button for consistency)
    NSButton *notifyBtn = [[NSButton alloc] initWithFrame:NSMakeRect(210, 100, 140, 50)];
    [notifyBtn setTitle:@"Show Alert"];
    [notifyBtn setFont:[NSFont fontWithName:@"Helvetica" size:14]];
    [notifyBtn setTextColor:[NSColor whiteColor]];
    [notifyBtn setBezelStyle:NSRoundedBezelStyle];  // Match sound button style
    [notifyBtn setBordered:YES];
    [notifyBtn setTarget:self];
    [notifyBtn setAction:@selector(showNotification:)];
    [notifyBtn setHighlightedColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.3]];
    [bgView addSubview:notifyBtn];
    [notifyBtn release];

    // 6. Add status label (subtle white text for user guidance)
    NSTextField *statusLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 50, 400, 20)];
    [statusLabel setStringValue:@"Click buttons to interact"];
    [statusLabel setFont:[NSFont fontWithName:@"Helvetica" size:12]];
    [statusLabel setTextColor:[NSColor colorWithCalibratedWhite:1.0 alpha:0.8]];  // Semi-transparent white
    [statusLabel setBackgroundColor:[NSColor clearColor]];
    [statusLabel setBordered:NO];
    [statusLabel setAlignment:NSCenterTextAlignment];
    [bgView addSubview:statusLabel];
    [statusLabel release];

    // Show window and bring to front
    [mainWindow makeKeyAndOrderFront:nil];
}

// Play sound using system 'aplay' (stable and compatible with all Linux/GNUstep)
- (void)playSound:(id)sender {
    NSString *soundPath = @"/usr/share/sounds/alsa/Front_Center.wav";
    
    // Check if sound file exists
    if (![[NSFileManager defaultManager] fileExistsAtPath:soundPath]) {
        [self showNotificationWithMessage:@"Sound file missing!"];
        return;
    }

    // Use NSTask to execute system command
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/aplay"];  // Path to aplay (ALSA sound tool)
    [task setArguments:[NSArray arrayWithObjects:soundPath, nil]];
    
    @try {
        [task launch];
        [task waitUntilExit];  // Wait for sound to finish playing
        [self showNotificationWithMessage:@"Sound played! 🎵"];
    } @catch (NSException *e) {
        [self showNotificationWithMessage:@"Sound failed! ❌"];
    }
    [task release];
}

// Show system notification with modern icon
- (void)showNotificationWithMessage:(NSString *)message {
    // Create notification (title, content, icon)
    NotifyNotification *n = notify_notification_new(
        "Beautiful UI Demo",          // Notification title
        [message UTF8String],         // Notification content (convert to C string)
        "dialog-apply"                // System icon (modern, supported)
    );
    
    // Auto-close after 3 seconds (less intrusive)
    notify_notification_set_timeout(n, 3000);

    // Show notification with error handling
    GError *error = NULL;
    if (!notify_notification_show(n, &error)) {
        NSLog(@"Notification error: %s", error->message);
        g_error_free(error);
    }
    
    // Release notification resource
    g_object_unref(G_OBJECT(n));
}

// Direct trigger for notification button
- (void)showNotification:(id)sender {
    [self showNotificationWithMessage:@"Hello! This is a modern alert 🔔"];
}

// Clean up resources to avoid memory leaks
- (void)dealloc {
    notify_uninit();  // Close libnotify
    [bgView release];
    [mainWindow release];
    [super dealloc];
}

@end

int main(int argc, const char **argv) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // Initialize GNUstep application
    [NSApplication load];
    NSApplication *app = [NSApplication sharedApplication];
    BeautifulUIDelegate *delegate = [[BeautifulUIDelegate alloc] init];
    [app setDelegate:delegate];
    
    // Start application event loop
    [app run];
    
    // Release resources
    [delegate release];
    [pool release];
    return 0;
}
